import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { ArrowLeft, Search as SearchIcon, Clock, Flag, Calendar, Bot } from 'lucide-react'
import { aiAPI, taskAPI } from '../services/api'
import { formatDate, getPriorityLabel, getCategoryIcon, getCategoryLabel } from '../utils'

export default function SearchPage() {
  const navigate = useNavigate()
  const [searchKeyword, setSearchKeyword] = useState('')
  const [searchResults, setSearchResults] = useState<any[]>([])
  const [showSuggestions] = useState(true)
  const [aiSearchResults, setAiSearchResults] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(false)

  // 固定的通用搜索建议
  const fixedSuggestions = [
    '高优先级',
    '今天到期的',
    '工作相关', 
    '学习计划'
  ]

  // 动态搜索建议状态
  const [, ] = useState<string[]>([])
  const [searchSuggestions, setSearchSuggestions] = useState<string[]>(fixedSuggestions)

  useEffect(() => {
    if (searchKeyword.trim()) {
      performSearch(searchKeyword)
    } else {
      loadAllTasks()
    }
  }, [searchKeyword])

  useEffect(() => {
    // 异步生成动态搜索建议，不阻塞页面渲染
    loadSearchSuggestionsWithCache()
  }, [])

  const loadAllTasks = async () => {
    try {
      const allTasks = await taskAPI.getAllTasks()
      setSearchResults(allTasks)
    } catch (error) {
      console.error('加载任务失败:', error)
      setSearchResults([])
    }
  }

  // 缓存相关常量
  const SEARCH_SUGGESTIONS_CACHE_KEY = 'aide_search_suggestions_cache'
  const SEARCH_SUGGESTIONS_TIME_KEY = 'aide_search_suggestions_time'
  const SEARCH_CACHE_DURATION = 10 * 60 * 1000 // 10分钟缓存

  // 带缓存的搜索建议加载
  const loadSearchSuggestionsWithCache = async () => {
    try {
      // 1. 先显示固定建议，确保页面立即可用
      setSearchSuggestions(fixedSuggestions)

      // 2. 检查缓存
      const cacheTime = localStorage.getItem(SEARCH_SUGGESTIONS_TIME_KEY)
      const cachedSuggestions = localStorage.getItem(SEARCH_SUGGESTIONS_CACHE_KEY)
      
      if (cacheTime && cachedSuggestions) {
        const now = Date.now()
        const cacheTimestamp = parseInt(cacheTime, 10)
        
        // 缓存未过期，直接使用
        if ((now - cacheTimestamp) < SEARCH_CACHE_DURATION) {
          const suggestions = JSON.parse(cachedSuggestions)
          setSearchSuggestions(suggestions)
          console.log('🚀 使用缓存的搜索建议:', suggestions.length, '条')
          return
        }
      }

      // 3. 缓存过期或不存在，异步生成新建议
      setTimeout(() => {
        generateDynamicSuggestionsOptimized()
      }, 100) // 延迟100ms，避免阻塞渲染
      
    } catch (error) {
      console.error('加载搜索建议失败:', error)
      setSearchSuggestions(fixedSuggestions)
    }
  }

  // 优化的动态建议生成（高性能版本）
  const generateDynamicSuggestionsOptimized = async () => {
    try {
      const allTasks = await taskAPI.getAllTasks()
      const taskCount = allTasks.length

      // 新用户直接使用扩展的固定建议
      if (taskCount < 5) {
        const newUserSuggestions = [...fixedSuggestions, '还没开始的', '已完成的']
        setSearchSuggestions(newUserSuggestions)
        cacheSearchSuggestions(newUserSuggestions)
        return
      }

      // 限制分析的任务数量，提高性能
      const recentTasks = allTasks.slice(0, Math.min(50, taskCount))
      const suggestions: string[] = []

      // 快速统计（使用Map提高性能）
      const stats = {
        categories: new Map<string, number>(),
        tags: new Map<string, number>(),
        priorities: new Map<string, number>(),
        overdueCount: 0,
        completedThisWeek: 0
      }

      const now = new Date()
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)

      // 单次遍历收集所有统计信息
      recentTasks.forEach(task => {
        // 分类统计
        if (task.category) {
          stats.categories.set(task.category, (stats.categories.get(task.category) || 0) + 1)
        }
        
        // 标签统计（限制处理数量）
        if (task.tags?.length > 0) {
          task.tags.slice(0, 3).forEach(tag => { // 只处理前3个标签
            if (tag?.trim()) {
              stats.tags.set(tag, (stats.tags.get(tag) || 0) + 1)
            }
          })
        }
        
        // 优先级统计
        if (task.priority) {
          stats.priorities.set(task.priority, (stats.priorities.get(task.priority) || 0) + 1)
        }
        
        // 状态统计
        if (task.dueDate && new Date(task.dueDate) < now && !task.completed) {
          stats.overdueCount++
        }
        
        if (task.completed && task.updatedAt && new Date(task.updatedAt) > weekAgo) {
          stats.completedThisWeek++
        }
      })

      // 快速生成建议（避免复杂排序）
      
      // 最常用分类（取前1个）
      let maxCategoryCount = 0
      let topCategory = ''
      stats.categories.forEach((count, category) => {
        if (count > maxCategoryCount && count >= 3) {
          maxCategoryCount = count
          topCategory = category
        }
      })
      
      if (topCategory) {
        const categoryLabel = getCategoryLabel(topCategory)
        suggestions.push(`${categoryLabel}相关`)
      }

      // 最常用标签（取前2个，限制长度）
      const topTags: [string, number][] = []
      stats.tags.forEach((count, tag) => {
        if (count >= 2 && tag.length <= 4) {
          topTags.push([tag, count])
        }
      })
      
      // 简单排序取前2个
      topTags.sort((a, b) => b[1] - a[1])
      topTags.slice(0, 2).forEach(([tag]) => {
        suggestions.push(`${tag}相关`)
      })

      // 状态建议（确保有对应数据才推荐）
      if ((stats.priorities.get('P1') || 0) >= 1) {
        suggestions.push('高优先级')
      }
      
      if (stats.overdueCount >= 1) {
        suggestions.push('已逾期的')
      }

      // 时间建议（检查是否有本周任务）
      const hasThisWeekTasks = recentTasks.some(task => {
        if (!task.dueDate) return false
        const taskDate = new Date(task.dueDate)
        const now = new Date()
        const weekStart = new Date(now)
        weekStart.setDate(now.getDate() - now.getDay())
        const weekEnd = new Date(weekStart)
        weekEnd.setDate(weekStart.getDate() + 6)
        return taskDate >= weekStart && taskDate <= weekEnd
      })
      
      if (hasThisWeekTasks) {
        suggestions.push('这周要完成的')
      }

      // 今天到期的任务
      const todayStr = new Date().toISOString().split('T')[0]
      const hasTodayTasks = recentTasks.some(task => task.dueDate === todayStr)
      if (hasTodayTasks) {
        suggestions.push('今天到期的')
      }

      // 合并建议（去重 + 限制数量）
      const finalSuggestions = Array.from(new Set([
        ...fixedSuggestions,
        ...suggestions.slice(0, 4) // 最多4个动态建议
      ])).slice(0, 8) // 总共最多8个建议

      setSearchSuggestions(finalSuggestions)
      cacheSearchSuggestions(finalSuggestions)
      
      console.log('⚡ 快速生成搜索建议:', {
        taskCount,
        analyzedCount: recentTasks.length,
        dynamicCount: suggestions.length,
        finalCount: finalSuggestions.length
      })
      
    } catch (error) {
      console.error('生成动态搜索建议失败:', error)
      setSearchSuggestions(fixedSuggestions)
    }
  }

  // 缓存搜索建议
  const cacheSearchSuggestions = (suggestions: string[]) => {
    try {
      localStorage.setItem(SEARCH_SUGGESTIONS_CACHE_KEY, JSON.stringify(suggestions))
      localStorage.setItem(SEARCH_SUGGESTIONS_TIME_KEY, Date.now().toString())
    } catch (error) {
      console.warn('缓存搜索建议失败:', error)
    }
  }

  const performSearch = async (keyword: string) => {
    try {
      const allTasks = await taskAPI.getAllTasks()
      
      // 使用智能搜索算法
      const searchResults = allTasks
        .map(task => intelligentSearch(task, keyword))
        .filter(result => result.score > 0)
        .sort((a, b) => b.score - a.score) // 按相关度排序
        .map(result => ({
          ...result.task,
          _searchScore: result.score,
          _searchMatches: result.matches
        }))

      setSearchResults(searchResults)
      
      // 输出搜索调试信息
      console.log('🔍 智能搜索结果:', {
        keyword,
        totalTasks: allTasks.length,
        matchedTasks: searchResults.length,
        topResults: searchResults.slice(0, 3).map(r => ({
          title: r.title,
          score: r._searchScore,
          matches: r._searchMatches
        }))
      })

    } catch (error) {
      console.error('搜索失败:', error)
      setSearchResults([])
    }
    
    // AI语义增强搜索（异步执行，不阻塞基础搜索）
    if (keyword.trim() && keyword.length > 2) {
      setIsLoading(true)
      try {
        const aiResult = await aiAPI.search(keyword)
        if (aiResult.success) {
          setAiSearchResults({
            ...aiResult,
            searchType: 'ai_enhanced',
            suggestions: aiResult.suggestions || [],
            searchTips: aiResult.searchTips || []
          })
        } else {
          console.warn('AI搜索失败:', aiResult.error)
          setAiSearchResults(null)
        }
      } catch (error) {
        console.error('AI搜索出错:', error)
        setAiSearchResults(null)
      } finally {
        setIsLoading(false)
      }
    } else {
      setAiSearchResults(null)
    }
  }

  // 智能搜索规则引擎
  const searchRules = {
    priority: {
      high: ['高优先级', '紧急', '重要', '急', 'P0', 'P1', '优先', '火急', '赶紧', '立即', '马上'],
      medium: ['普通优先级', '一般', '正常', 'P2', '中等'],
      low: ['低优先级', '不急', '可延期', 'P3', '后面做', '有空再做', '慢慢来']
    },
    time: {
      today: ['今天', '今日', '当天', '本日'],
      overdue: ['逾期', '过期', '延期', '超时', '迟了', '晚了'],
      thisWeek: ['这周', '本周', '这星期', '本星期', '周内'],
      nextWeek: ['下周', '下星期', '下个星期'],
      thisMonth: ['这个月', '本月', '月内'],
      urgent: ['紧急', '急', '赶紧', '马上', '立即']
    },
    status: {
      completed: ['已完成', '完成的', '做完', '结束', '搞定', '完毕'],
      pending: ['未完成', '没做', '还没开始', '进行中', '待办', '要做的', '没搞定'],
      inProgress: ['进行中', '正在做', '在做', '处理中']
    },
    category: {
      work: ['工作', '上班', '公司', '职场', '业务', '项目', '任务'],
      learning: ['学习', '培训', '课程', '教育', '技能', '知识', '书'],
      health: ['健康', '运动', '锻炼', '体检', '医院', '身体'],
      personal: ['个人', '私人', '家庭', '生活', '自己的']
    },
    content: {
      meeting: ['会议', '开会', '讨论', '沟通', '汇报', '例会', '评审'],
      finance: ['财务', '钱', '预算', '报销', '成本', '收入', '支出'],
      document: ['文档', '报告', '材料', 'PPT', '演示', '总结'],
      coding: ['代码', '编程', '开发', '程序', '系统', '功能'],
      checkin: ['打卡', '签到', '上班', '下班', '考勤']
    }
  }

  // 智能搜索匹配函数
  // 智能搜索核心算法
  const intelligentSearch = (task: any, keyword: string) => {
    const lowerKeyword = keyword.toLowerCase().trim()
    let score = 0
    const matches: string[] = []

    // 1. 精确匹配（最高权重）
    const exactMatch = exactSearchMatch(task, lowerKeyword)
    if (exactMatch.matched) {
      score += exactMatch.score
      matches.push(...exactMatch.reasons)
    }

    // 2. 语义匹配（高权重）
    const semanticMatch = semanticSearchMatch(task, lowerKeyword)
    if (semanticMatch.matched) {
      score += semanticMatch.score
      matches.push(...semanticMatch.reasons)
    }

    // 3. 模糊匹配（中等权重）
    const fuzzyMatch = fuzzySearchMatch(task, lowerKeyword)
    if (fuzzyMatch.matched) {
      score += fuzzyMatch.score
      matches.push(...fuzzyMatch.reasons)
    }

    // 4. 上下文匹配（低权重）
    const contextMatch = contextSearchMatch(task, lowerKeyword)
    if (contextMatch.matched) {
      score += contextMatch.score
      matches.push(...contextMatch.reasons)
    }

    return { score, matches, task }
  }

  // 精确匹配
  const exactSearchMatch = (task: any, keyword: string) => {
    let score = 0
    const reasons: string[] = []

    // 标题完全匹配
    if (task.title?.toLowerCase().includes(keyword)) {
      score += 100
      reasons.push('标题匹配')
    }

    // 标签完全匹配
    if (task.tags?.some((tag: string) => tag.toLowerCase().includes(keyword))) {
      score += 80
      reasons.push('标签匹配')
    }

    // 描述匹配
    if (task.description?.toLowerCase().includes(keyword)) {
      score += 60
      reasons.push('描述匹配')
    }

    return { matched: score > 0, score, reasons }
  }

  // 语义匹配
  const semanticSearchMatch = (task: any, keyword: string) => {
    let score = 0
    const reasons: string[] = []

    // 优先级语义匹配
    if (matchesAnyRule(keyword, searchRules.priority.high)) {
      if (task.priority === 'P0' || task.priority === 'P1') {
        score += 90
        reasons.push('高优先级匹配')
      }
    }

    if (matchesAnyRule(keyword, searchRules.priority.low)) {
      if (task.priority === 'P3') {
        score += 90
        reasons.push('低优先级匹配')
      }
    }

    // 时间语义匹配
    const today = new Date().toISOString().split('T')[0]
    if (matchesAnyRule(keyword, searchRules.time.today)) {
      if (task.dueDate === today) {
        score += 95
        reasons.push('今日任务匹配')
      }
    }

    if (matchesAnyRule(keyword, searchRules.time.overdue)) {
      if (task.dueDate && new Date(task.dueDate) < new Date() && !task.completed) {
        score += 95
        reasons.push('逾期任务匹配')
      }
    }

    // 状态语义匹配
    if (matchesAnyRule(keyword, searchRules.status.completed)) {
      if (task.completed) {
        score += 85
        reasons.push('完成状态匹配')
      }
    }

    if (matchesAnyRule(keyword, searchRules.status.pending)) {
      if (!task.completed) {
        score += 85
        reasons.push('待办状态匹配')
      }
    }

    // 分类语义匹配
    Object.entries(searchRules.category).forEach(([category, keywords]) => {
      if (matchesAnyRule(keyword, keywords) && task.category === category) {
        score += 80
        reasons.push(`${getCategoryLabel(category)}分类匹配`)
      }
    })

    // 内容语义匹配
    Object.entries(searchRules.content).forEach(([contentType, keywords]) => {
      if (matchesAnyRule(keyword, keywords)) {
        const titleMatch = keywords.some(kw => task.title?.includes(kw))
        const tagMatch = keywords.some(kw => task.tags?.some((tag: string) => tag.includes(kw)))
        
        if (titleMatch || tagMatch) {
          score += 75
          reasons.push(`${contentType}内容匹配`)
        }
      }
    })

    return { matched: score > 0, score, reasons }
  }

  // 模糊匹配
  const fuzzySearchMatch = (task: any, keyword: string) => {
    let score = 0
    const reasons: string[] = []

    // 拼音匹配（简化版）
    const pinyinMatch = checkPinyinMatch(task, keyword)
    if (pinyinMatch) {
      score += 40
      reasons.push('拼音匹配')
    }

    // 部分匹配
    const partialMatch = checkPartialMatch(task, keyword)
    if (partialMatch.score > 0) {
      score += partialMatch.score
      reasons.push('部分匹配')
    }

    // 相似度匹配
    const similarityMatch = checkSimilarityMatch(task, keyword)
    if (similarityMatch.score > 0) {
      score += similarityMatch.score
      reasons.push('相似度匹配')
    }

    return { matched: score > 0, score, reasons }
  }

  // 上下文匹配
  const contextSearchMatch = (task: any, keyword: string) => {
    let score = 0
    const reasons: string[] = []

    // 时间上下文
    const timeContext = getTimeContext(task)
    if (timeContext.includes(keyword)) {
      score += 30
      reasons.push('时间上下文')
    }

    // 项目上下文
    const projectContext = getProjectContext(task)
    if (projectContext.includes(keyword)) {
      score += 25
      reasons.push('项目上下文')
    }

    return { matched: score > 0, score, reasons }
  }

  // 辅助函数
  const matchesAnyRule = (keyword: string, rules: string[]) => {
    return rules.some(rule => keyword.includes(rule) || rule.includes(keyword))
  }

  const checkPinyinMatch = (task: any, keyword: string) => {
    // 简化的拼音匹配逻辑
    const pinyinMap: { [key: string]: string[] } = {
      'gongzuo': ['工作'], 'huiyi': ['会议'], 'caiwu': ['财务'],
      'daka': ['打卡'], 'xiaban': ['下班'], 'jinjí': ['紧急']
    }
    
    return Object.entries(pinyinMap).some(([pinyin, chars]) => 
      keyword.includes(pinyin) && chars.some(char => 
        task.title?.includes(char) || task.tags?.includes(char)
      )
    )
  }

  const checkPartialMatch = (task: any, keyword: string) => {
    let score = 0
    const words = keyword.split(/\s+/)
    
    words.forEach(word => {
      if (word.length >= 2) {
        if (task.title?.includes(word)) score += 20
        if (task.tags?.some((tag: string) => tag.includes(word))) score += 15
      }
    })
    
    return { score }
  }

  const checkSimilarityMatch = (task: any, keyword: string) => {
    let score = 0
    const taskText = `${task.title} ${task.tags?.join(' ') || ''}`.toLowerCase()
    
    // 简化的相似度算法
    const similarity = calculateSimilarity(taskText, keyword)
    if (similarity > 0.3) {
      score += Math.floor(similarity * 50)
    }
    
    return { score }
  }

  const calculateSimilarity = (text1: string, text2: string) => {
    const words1 = new Set(text1.split(/\s+/))
    const words2 = new Set(text2.split(/\s+/))
    const intersection = new Set([...words1].filter(x => words2.has(x)))
    return intersection.size / Math.max(words1.size, words2.size)
  }

  const getTimeContext = (task: any) => {
    const contexts = []
    if (task.dueDate) {
      const date = new Date(task.dueDate)
      const today = new Date()
      const diffDays = Math.ceil((date.getTime() - today.getTime()) / (1000 * 3600 * 24))
      
      if (diffDays === 0) contexts.push('今天', '今日')
      if (diffDays === 1) contexts.push('明天')
      if (diffDays < 0) contexts.push('逾期', '过期')
      if (diffDays >= 0 && diffDays <= 7) contexts.push('本周', '这周')
    }
    return contexts.join(' ')
  }

  const getProjectContext = (task: any) => {
    // 基于标签和分类推断项目上下文
    const contexts = []
    if (task.category) contexts.push(getCategoryLabel(task.category))
    if (task.tags) contexts.push(...task.tags)
    return contexts.join(' ')
  }

  const handleSuggestionClick = (suggestion: string) => {
    setSearchKeyword(suggestion)
    performSearch(suggestion)
  }

  const handleTaskClick = (taskId: string) => {
    navigate(`/task/${taskId}`)
  }

  const getSearchResultIcon = (keyword: string) => {
    if (keyword.includes('优先级')) return <Flag size={16} />
    if (keyword.includes('时间') || keyword.includes('到期')) return <Clock size={16} />
    if (keyword.includes('会议') || keyword.includes('开会')) return <Calendar size={16} />
    return <SearchIcon size={16} />
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* 搜索头部 */}
      <div className="sticky top-0 z-10 bg-theme-bg/95 backdrop-blur-sm border-b border-theme-border/60 shadow-sm">
        <div className="flex items-center px-4 sm:px-6 py-4">
          <button
            onClick={() => navigate('/')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all mr-3 touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          
          <div className="flex-1 relative">
            <SearchIcon size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
            <input
              type="text"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              placeholder="搜索任务、备注..."
              className="w-full pl-10 pr-4 py-3 bg-theme-bg-secondary border border-theme-border rounded-xl text-theme-text placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-theme-bg transition-all"
              autoFocus
            />
          </div>
        </div>
      </div>

      {/* 搜索建议 */}
      {!searchKeyword && showSuggestions && (
        <div className="px-4 sm:px-6 py-4">
          <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
            <h3 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
              <div className="w-1 h-4 bg-orange-500 rounded-full"></div>
              常用搜索
            </h3>
            <div className="flex flex-wrap gap-2">
              {searchSuggestions.map((suggestion, index) => (
                <button
                  key={index}
                  onClick={() => handleSuggestionClick(suggestion)}
                  className="px-3 py-2 bg-theme-bg-secondary text-theme-text-secondary text-sm rounded-xl hover:bg-blue-50 hover:text-blue-700 hover:border-blue-200 border border-theme-border transition-all flex items-center gap-2"
                >
                  {getSearchResultIcon(suggestion)}
                  {suggestion}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* AI智能搜索结果 */}
      {aiSearchResults && searchKeyword && (
        <div className="px-4 sm:px-6 py-4">
          <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
            <div className="flex items-center gap-2 mb-4">
              <div className="w-1 h-4 bg-blue-500 rounded-full"></div>
              <Bot size={16} className="text-blue-600" />
              <h3 className="text-sm font-semibold text-theme-text">AI智能分析</h3>
              {isLoading && (
                <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
              )}
            </div>
            
            {aiSearchResults.intent && (
              <div className="mb-4 p-3 bg-blue-50 rounded-xl border border-blue-200">
                <p className="text-sm text-blue-800 flex items-center gap-2">
                  <span className="text-base">🎯</span>
                  {aiSearchResults.intent}
                </p>
              </div>
            )}
            
            {aiSearchResults.suggestions && aiSearchResults.suggestions.length > 0 && (
              <div className="mb-4">
                <h4 className="text-xs font-semibold text-theme-text mb-3">相关建议</h4>
                <div className="space-y-2">
                  {aiSearchResults.suggestions.map((suggestion: string, index: number) => (
                    <div key={index} className="text-sm text-theme-text-secondary bg-theme-bg-secondary p-3 rounded-xl border border-theme-border flex items-start gap-2">
                      <span className="text-base mt-0.5">💡</span>
                      {suggestion}
                    </div>
                  ))}
                </div>
              </div>
            )}
            
            {aiSearchResults.searchTips && aiSearchResults.searchTips.length > 0 && (
              <div>
                <h4 className="text-xs font-semibold text-theme-text mb-3">搜索技巧</h4>
                <div className="flex flex-wrap gap-2">
                  {aiSearchResults.searchTips.map((tip: string, index: number) => (
                    <span key={index} className="text-xs text-theme-text-secondary bg-theme-bg-secondary px-3 py-1.5 rounded-full border border-theme-border font-medium">
                      {tip}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 搜索结果 */}
      <div className="px-4 sm:px-6 pb-6">
        {searchKeyword && (
          <div className="mb-4">
            <h3 className="text-sm font-semibold text-theme-text flex items-center gap-2">
              <div className="w-1 h-4 bg-green-500 rounded-full"></div>
              搜索结果
              <span className="px-2 py-1 bg-theme-bg-tertiary text-theme-text-secondary text-xs rounded-full font-semibold">
                {searchResults.length}
              </span>
            </h3>
            <p className="text-xs text-theme-text-muted mt-2">
              关键词: "{searchKeyword}"
            </p>
          </div>
        )}

        {searchResults.length === 0 ? (
          <div className="text-center py-16">
            <div className="w-16 h-16 bg-theme-bg-tertiary rounded-full flex items-center justify-center mx-auto mb-4">
              <SearchIcon size={24} className="text-slate-400" />
            </div>
            <h3 className="text-lg font-semibold text-theme-text mb-2">
              没有找到相关任务
            </h3>
            <p className="text-sm text-theme-text-muted">
              尝试使用不同的关键词或查看搜索建议
            </p>
          </div>
        ) : (
          <div className="space-y-3">
            {searchResults.map((task) => (
              <div
                key={task.id}
                onClick={() => handleTaskClick(task.id)}
                className="bg-theme-bg rounded-2xl border border-theme-border/60 p-4 hover:shadow-md hover:border-theme-border/60 transition-all cursor-pointer shadow-sm"
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-2">
                      <h4 className="font-semibold text-theme-text">
                        {task.title}
                      </h4>
                      {task._searchScore && (
                        <span className="text-xs px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full font-medium">
                          {Math.round(task._searchScore)}%
                        </span>
                      )}
                    </div>
                    
                    {/* 搜索匹配原因 */}
                    {task._searchMatches && task._searchMatches.length > 0 && (
                      <div className="flex flex-wrap gap-1 mb-2">
                        {task._searchMatches.slice(0, 3).map((match: any, index: number) => (
                          <span
                            key={index}
                            className="text-xs px-2 py-0.5 bg-green-50 text-green-700 rounded-full border border-green-200"
                          >
                            ✓ {match}
                          </span>
                        ))}
                        {task._searchMatches.length > 3 && (
                          <span className="text-xs px-2 py-0.5 text-green-600">
                            +{task._searchMatches.length - 3}个匹配
                          </span>
                        )}
                      </div>
                    )}
                    
                    {task.description && (
                      <p className="text-sm text-theme-text-secondary mb-3 line-clamp-2">
                        {task.description}
                      </p>
                    )}
                    
                    <div className="flex items-center flex-wrap gap-2">
                      <span className="flex items-center gap-1 text-xs text-theme-text-secondary bg-theme-bg-tertiary px-2 py-1 rounded-full">
                        {(() => {
                          const IconComponent = getCategoryIcon(task.category)
                          return <IconComponent size={12} />
                        })()}
                        {getCategoryLabel(task.category)}
                      </span>
                      
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                        task.priority === 'P0' ? 'bg-red-100 text-red-700' :
                        task.priority === 'P1' ? 'bg-orange-100 text-orange-700' :
                        task.priority === 'P2' ? 'bg-blue-100 text-blue-700' :
                        'bg-theme-bg-tertiary text-theme-text-secondary'
                      }`}>
                        {getPriorityLabel(task.priority)}
                      </span>
                      
                      {task.dueDate && (
                        <span className="flex items-center gap-1 text-xs text-theme-text-secondary bg-theme-bg-tertiary px-2 py-1 rounded-full">
                          <Calendar size={12} />
                          {formatDate(task.dueDate)}
                        </span>
                      )}

                      {task.tags && task.tags.length > 0 && (
                        <>
                          {task.tags.slice(0, 2).map((tag: string, index: number) => (
                            <span
                              key={index}
                              className="text-xs px-2 py-1 bg-theme-bg-tertiary text-theme-text-secondary rounded-full"
                            >
                              #{tag}
                            </span>
                          ))}
                          {task.tags.length > 2 && (
                            <span className="text-xs text-slate-400">
                              +{task.tags.length - 2}
                            </span>
                          )}
                        </>
                      )}
                    </div>
                  </div>
                  
                  {task.completed && (
                    <div className="ml-3 flex-shrink-0">
                      <div className="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center shadow-sm">
                        <span className="text-white text-xs">✓</span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
